package com.lm.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.annotations.Api;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.CrossOrigin;
import com.lm.pojo.ChatMessage;
import com.lm.util.WebSocketUtils;
import org.springframework.web.bind.annotation.RestController;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;

@RestController
@Api(tags = "聊天室")
@Component
@CrossOrigin(origins = "*")
@ServerEndpoint("/chat/{username}")
public class ChatServerEndPoint {
    // 修复日志记录器引用的类名
    private static final Logger logger = LoggerFactory.getLogger(ChatServerEndPoint.class);
    private static final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * @description: 打开WebSocket连接时触发的事件
     * @param: username
session
     * @return: void
     * @author 32477
     * @date: 2025/9/19 11:15
     */
    @OnOpen
    public void openSession(@PathParam("username") String username, Session session) {
        WebSocketUtils.USER_SESSIONS.put(username, session);
        
        // 发送欢迎消息给新用户
        ChatMessage welcomeMessage = new ChatMessage("SYSTEM", "system", username, "欢迎来到聊天室！");
        WebSocketUtils.sendObjectMessage(session, welcomeMessage);
        
        // 通知其他用户有新用户加入
        ChatMessage joinMessage = new ChatMessage("ALL", "system", null, "用户[" + username + "] 来到聊天室！");
        final String joinMessageStr; // 改为final
        try {
            joinMessageStr = objectMapper.writeValueAsString(joinMessage);
        } catch (Exception e) {
            logger.error("JSON序列化失败", e);
            return; // 添加return防止后续使用未初始化的变量
        }
        
        // 向除新用户外的所有用户发送通知
        WebSocketUtils.USER_SESSIONS.forEach((name, sess) -> {
            if (!name.equals(username)) {
                WebSocketUtils.sendMessage(sess, joinMessageStr);
            }
        });
        
        logger.info("用户登录：" + username);
    }

    /**
     * @description: 收到WebSocket消息时触发的事件
     * @param: username message
     * @return: void
     * @author 32477
     * @date: 2025/9/19 11:15
     */
    @OnMessage
    public void onMessage(@PathParam("username") String username, String message) {
        logger.info("收到消息：" + message + "，来自用户：" + username);
        
        try {
            // 解析JSON消息
            ChatMessage chatMessage = objectMapper.readValue(message, ChatMessage.class);
            chatMessage.setFrom(username); // 确保发送者信息正确
            
            // 保留或设置正确的角色信息
            // 如果消息中没有角色信息，可以根据用户类型设置默认角色
            // 这里简单保留原消息中的角色信息

            if ("ALL".equals(chatMessage.getType())) {
                // 广播消息
                String broadcastMsg = objectMapper.writeValueAsString(chatMessage);
                WebSocketUtils.sendMessageAll(broadcastMsg);
            } else if ("USER".equals(chatMessage.getType())) {
                // 点对点消息 - 直接转发完整的消息对象，包括角色信息
                boolean sent = WebSocketUtils.sendObjectMessageToUser(chatMessage.getTo(), chatMessage);

                // 发送状态确认给发送者
                ChatMessage statusMessage = new ChatMessage("STATUS", "system", username, "");
                WebSocketUtils.sendObjectMessageToUser(username, statusMessage);
            }

        } catch (Exception e) {
            logger.error("处理消息异常", e);
            // 发送错误消息给用户
            ChatMessage errorMessage = new ChatMessage("ERROR", "system", username, "消息格式错误");
            try {
                WebSocketUtils.sendObjectMessageToUser(username, errorMessage);
            } catch (Exception ex) {
                logger.error("发送错误消息失败", ex);
            }
        }
    }

    @OnClose
    public void onClose(@PathParam("username") String username, Session session) {
        //当前的Session 移除
        WebSocketUtils.USER_SESSIONS.remove(username);
        //并且通知其他人当前用户已经离开聊天室了
        try {
            ChatMessage leaveMessage = new ChatMessage("ALL", "system", null, "用户[" + username + "] 已经离开聊天室了！");
            String leaveMessageStr = objectMapper.writeValueAsString(leaveMessage);
            WebSocketUtils.sendMessageAll(leaveMessageStr);
        } catch (Exception e) {
            logger.error("发送离开消息失败", e);
        }
        
        try {
            session.close();
        } catch (IOException e) {
            logger.error("onClose error", e);
        }
    }

    @OnError
    public void onError(Session session, Throwable throwable) {
        try {
            session.close();
        } catch (IOException e) {
            logger.error("onError excepiton", e);
        }
        logger.info("Throwable msg " + throwable.getMessage());
    }
}